import React, { useState, useEffect, useRef } from 'react';
import { ReloadOutlined } from '@ant-design/icons';
import type { ProColumns } from '@ant-design/pro-table';
import { useModel } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Divider, FormInstance, Popover, Modal, Form, Spin, Popconfirm } from 'antd';
import ProForm from '@ant-design/pro-form';
import { EditableProTable, ActionType } from '@ant-design/pro-table';
import {
  getRentSettleInfo,
  getOrderRentDetail,
  updateSettleStatus,
  deleteItem,
  updateItem,
  getRentSum,
  startSettle,
  managerCancel,
} from '@/services/order/api';
import { isNull, MsgType, showMsg, isSupportSticky } from '@/utils/utils';
import PopoverContent from '@/components/PopoverContent/Index';
import Detail from './Detail';
import RentListDialog from './rentListDialog';
import { history } from 'umi';
import './style.less';
import BreadcrumbDept from '@/components/BreadcrumbDept';
import PermissionControl from '@/components/PermissionControl';
import PatientForm from './comm/PatientForm';
import ChoicePatient from '@/components/ChoicePatient';

interface RentSettleProps {
  location?: any;
}
/**
 * 院内租赁结算
 * @param props
 * @returns
 */
const RentSettle: React.FC<RentSettleProps> = (props) => {
  const { admission_num, type } = props.location.query;
  const { initialState } = useModel('@@initialState');
  const [goodsList, setGoodsList] = useState<any[]>([]);
  const formRef = useRef<FormInstance>();
  const [form] = Form.useForm();
  const actionRef = useRef<ActionType>();
  const settleActionRef = useRef<ActionType>();
  const [dialogVisible, setDialogVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<any>({});
  const [rentSum, setRentSum] = useState<any>({});

  const [patientInfo, setPatientInfo] = useState<any>({});

  const [params, setParams] = useState<any>({ admission_num });

  const [cansett, setCanSett] = useState<boolean>(false);

  const [settleLoading, setSettleLoading] = useState<boolean>(false);

  const [printing, setPrinting] = useState(false);

  // 租赁清单弹窗
  const [rentListDialog, setRentListDialog] = useState<boolean>(false);

  const [line, setLine] = useState<number>(-1);
  const [visible, setVisible] = useState<boolean>(false);

  const [cancelLoading, setCancelLoading] = useState<boolean>(false);

  const patientRef = useRef(); // 获取患者信息的实例

  const [clickRow, setClickRow] = useState(''); // 当前选中的行编号，用于定位颜色
  const [clickRow1, setClickRow1] = useState(''); // 当前选中的行编号，用于定位颜色

  const { confirm } = Modal;

  const columns: ProColumns<any>[] = [
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      editable: false,
      width: 200,
    },
    {
      title: '登记时间',
      dataIndex: 'register_time',
      editable: false,
      width: 160,
    },
    {
      title: '租赁周期',
      dataIndex: 'lease_cycle',
      width: 70,
      valueType: 'select',
      valueEnum: {
        H: '按小时',
        D: '按天',
      },
      editable: false,
    },
    {
      title: '周期长度',
      dataIndex: 'cycle_num',
      width: 70,
      align: 'right',
      valueType: 'digit',
      fieldProps: {
        // precision: 0,
        // min: 1,
        style: {
          width: '100%',
        },
      },
      formItemProps: (form, { rowKey, rowIndex }) => {
        return {
          rules: [
            {
              required: true,
              message: '此项是必填项',
            },
            {
              validator: (_, value) => {
                if (value <= 0) {
                  return Promise.reject(new Error('不能为0'));
                }
                return Promise.resolve();
              },
              message: '周期长度不能为0',
            },
          ],
        };
      },
    },
    {
      title: '单价',
      dataIndex: 'goods_price',
      width: 80,
      editable: false,
      valueType: 'money',
      align: 'right',
    },
    {
      title: '数量',
      dataIndex: 'goods_num',
      width: 60,
      align: 'right',
      valueType: 'digit',
      fieldProps: {
        // min: 1,
        precision: 0,
        style: {
          width: '100%',
        },
      },
      formItemProps: (form, { rowKey, rowIndex }) => {
        return {
          rules: [
            {
              required: true,
              message: '此项是必填项',
            },
            {
              validator: (_, value) => {
                if (value <= 0) {
                  return Promise.reject(new Error('不能为0'));
                }
                return Promise.resolve();
              },
              message: '数量不能为0',
            },
          ],
        };
      },
    },
    {
      title: '价格',
      dataIndex: 'goods_total_price',
      valueType: 'money',
      align: 'right',
      width: 80,
      editable: false,
    },
    {
      title: '租赁状态',
      dataIndex: 'status',
      valueType: 'select',
      width: 60,
      valueEnum: {
        N: '正常',
        D: '作废',
      },
      editable: false,
    },
    {
      title: '结算状态',
      dataIndex: 'sett_status',
      width: 70,
      valueType: 'select',
      valueEnum: {
        U: '未结算',
        W: '待结算',
        P: '已结算',
        G: '结算中',
      },
      editable: false,
      render: (val, record) => {
        if (record.status === 'D') {
          return '-';
        }
        return val;
      }
    },
    {
      title: '操作',
      align: 'center',
      // fixed: 'right',
      fixed: isSupportSticky() ? 'right' : '',
      width: 90,
      valueType: 'option',
      render: (_, entity, index) => {
        // 已结算、待结算、结算中
        if (entity.sett_status === 'P' || 
        entity.sett_status === 'W' || 
        entity.sett_status === 'G') {
          return '';
        }
        // 租赁状态为正常的才能操作
        if (entity.status === 'N') {
          return [
            <PermissionControl key="edit" action_id="400402008">
              <a onClick={() => {
                  console.log(entity);
                  actionRef.current?.startEditable(entity.id);
                }}
              >
                修改
              </a>
            </PermissionControl>,
            <PermissionControl key="delete" action_id="400402012">
              <Popover
                trigger="click"
                visible={visible && line === index}
                placement="rightTop"
                onVisibleChange={setVisible}
                content={
                  <PopoverContent
                    placeholder="请输入作废原因"
                    confirmText="确认作废"
                    loading={settleLoading}
                    onCancel={() => {
                      setVisible(false);
                      setLine(-1);
                    }}
                    onConfirm={async () => {
                      setSettleLoading(true);
                      try {
                        await deleteItem(entity.detail_id);
                        showMsg('已作废', MsgType.SUCCESS);
                        setSettleLoading(false);
                        setVisible(false);
                        setLine(-1);
                        fetchSum(admission_num);
                        actionRef?.current?.reload();
                      } catch (error) {
                        setSettleLoading(false);
                        showMsg(error?.data?.errmsg);
                      }
                    }}
                  />
                }
              >
                <a onClick={() => {
                    setVisible(true);
                    setLine(index);
                  }}>
                  作废
                </a>
              </Popover>
            </PermissionControl>
          ];
        }
      },
    },
  ];
  const cancelCurOrder = async(entity, index) => {
    setCancelLoading(true);
    if (entity.manager_flag === 'Y') {
      await managerCancel(entity.manager_order_id).then(res => {
        setCancelLoading(true);
        showMsg('已取消结算', 'success');
        actionRef.current?.reload();
        settleActionRef.current?.reload();
      }).catch(error => {
        showMsg(error?.data?.errmsg)
      });
    } else {
      setCancelLoading(true);
      setLine(index);
      await updateSettleInfo(entity.manager_flag, {
        sett_id: entity.sett_id,
        manager_order_id: entity.manager_order_id,
        sett_status: 'U',
      }, '已取消结算');
      setCancelLoading(false);
      setLine(-1);
      actionRef.current?.reload();
      settleActionRef.current?.reload();
    }
  }


  const settleColumns: ProColumns<any>[] = [
    {
      title: '结算时间',
      dataIndex: 'sett_time',
    },
    {
      title: '结算金额',
      dataIndex: 'sett_price',
      valueType: 'money',
      align: 'right',
    },
    {
      title: '结算状态',
      dataIndex: 'sett_status',
      valueType: 'select',
      valueEnum: {
        U: '未结算',
        W: '待结算',
        P: '已结算',
        G: '结算中',
      },
    },
    {
      title: '单据创建人',
      dataIndex: 'create_user_name',
    },
    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      render: (_, entity, index) => {
        const { manager_flag } = entity;
        return [
          <PermissionControl key="view" action_id="400402009">
            <Button type='link' onClick={() => {
                setCurrentRow(entity);
                setLine(index);
                setDialogVisible(true);
              }}>
              查看
            </Button>
          </PermissionControl>,
          (entity.sett_status === 'U' && manager_flag !== 'Y') &&
          <PermissionControl key="settle" action_id="400402010">
            <Button type='link' onClick={() => {
                setCurrentRow(entity);
                setDialogVisible(true);
              }}
            >
              结算
            </Button>
          </PermissionControl>,
          entity.sett_status !== 'P' &&
          <PermissionControl key="cancel" action_id="400402011">
            <Popconfirm
              placement="topRight"
              key="cancel"
              title={manager_flag === 'Y' ? '该笔订单已经通过出院办结发起结算，是否确认取消？' : ''}
              onConfirm={async () => cancelCurOrder(entity, index)}
              okText="确认取消"
              disabled={entity.manager_flag !== 'Y'}
              cancelText="再想想">
              <Button
                loading={cancelLoading && line === index}
                type="link"
                onClick={() => {
                  if (manager_flag !== 'Y') {
                  cancelCurOrder(entity, index)
                  }
                }}>取消</Button>
              </Popconfirm>
          </PermissionControl>
        ];
      },
    },
  ];

  const optCallback = (data: any) => {
    setDialogVisible(false);

    // 提交支付
    const orderSumbitConfig = {
      title: '',
      content: `订单提交成功，请在【${data?.pay_valid_time}】前完成缴费`,
      cancelText: '知道了',
      okText: '打印结算单',
      onOk() {
        setPrinting(true);
        setDialogVisible(true);
      },
      onCancel() {
        setDialogVisible(true);
      },
    };
    
    actionRef.current?.reload();
    settleActionRef.current?.reload();
    confirm(orderSumbitConfig);
  };

  useEffect(() => {
    formRef.current?.setFieldsValue({
      ward_name: initialState?.currentUser?.ward_name,
    });
  }, []);

  const fetchSum = (admission_num: string) => {
    getRentSum({ admission_num }).then((data: any) => {
      setRentSum(data);
    });
  };

  useEffect(() => {
    if (admission_num) {
      fetchSum(admission_num);
    }
  }, []);

  useEffect(() => {
    console.log(patientInfo);
    formRef.current?.setFieldsValue({
      admission_num: patientInfo.admission_num || admission_num,
    });
  }, [patientInfo]);

  /**
   * 更新结算信息
   */
  const updateSettleInfo = async (flag, params: { manager_order_id: string, sett_id: string; sett_status: string }, tip) => {
    if (settleLoading) {
      return;
    }
    setSettleLoading(true);
    try {
      if (flag === 'Y') {
        await managerCancel(params.manager_order_id)
      } else {
        await updateSettleStatus(params)
      }
      
      setSettleLoading(false);
      if (params.sett_status === 'U') {
        showMsg(tip, MsgType.SUCCESS);
        actionRef.current?.reload();
        settleActionRef.current?.reload();
      }
    } catch (error) {
      setSettleLoading(false);
      showMsg(error?.data?.errmsg);
    }
  };

  console.log('patientInfopatientInfo', patientInfo)

  return (
    <PageContainer
      className="rent-detail-container"
      title="院内租赁结算"
      extra={[<BreadcrumbDept />]}
      breadcrumb={{}}
      onBack={() =>
        history.replace({
          pathname: '/order/rent',
          query: {
            from: 'detail',
            type: '2',
            admission_num
          },
        })
      }
    >
      <div className="service-record-rent">
        <div className="header">
          <div className="title">1.患者信息</div>
        </div>
        <Divider style={{ margin: '10px 0' }} />
        {/* <PatientForm
          type={type}
          // orderDetail={orderDetail}
          ref={patientRef}
          onSubmit={(e) => {
            setParams({ admission_num: e});
            fetchSum(e);
            actionRef.current?.reload();
            settleActionRef.current?.reload();
          }}
          patient={patientInfo}
          setInfo={setPatientInfo}
          onReset={() => {
            setPatientInfo({});
            setParams('');
            setRentSum({});
            actionRef.current?.reload();
            settleActionRef.current?.reload();
          }}
        /> */}
        <ChoicePatient
          caseNoKey={'case_no'}
          ref={patientRef}
          fromTo='rent'
          showMore={false}
          onChoice={async(info) => {
            setParams({ admission_num: info.visit_no });
            setPatientInfo(info);
            fetchSum(info.visit_no);
            actionRef.current?.reload();
            settleActionRef.current?.reload();
          }}
          changePatient={() => {
            setPatientInfo({});
            setParams('');
            setRentSum({});
            patientRef?.current?.clear();
            actionRef.current?.reload();
            settleActionRef.current?.reload();
          }}
        />
      </div>

      <div className="service-record-rent" style={{ marginTop: -20 }}>
        <div className="header">
          <div className="title">2.物品信息</div>
          <div className="btns">
            未结算金额：
            <span className="fwb" style={{ color: '#FAAD15' }}>
              {rentSum.total_sett_wait_price || 0}
            </span>
            （元） 已结算金额：
            <span className="fwb" style={{ color: '#52C41A' }}>
              {rentSum.total_sett_suc_price || 0}
            </span>
            （元）
          </div>
        </div>
        <Divider style={{ margin: '10px 0 0' }} />
        <Spin spinning={settleLoading}>
          <EditableProTable<any, any>
            rowKey="id"
            bordered
            className="goods-pro-table"
            style={{ marginTop: -5 }}
            params={params}
            
            request={async (params1) => {
              try {
                if (isNull(params.admission_num)) {
                  return {
                    data: [],
                    total: 0,
                    success: true,
                  };
                }
                params1 = Object.assign({}, { current: 1, pageSize: 1000, admission_num: params.admission_num });
                const data = await getOrderRentDetail(params1);
                const list = data.record_list.map((item: any) => {
                  return {
                    ...item,
                    visible: false,
                    id: item.detail_id,
                  };
                });

                setCanSett(data.can_sett === 'Y');

                const patientDetail = {
                  ...patientInfo,
                  admission_status: data.admission_status,
                  admission_num: params.admission_num,
                  patient_id: data.patient_id,
                  patient_name: data.patient_name,
                  visit_no: params.admission_num,
                };
                console.log('patientDetail', patientDetail, patientInfo)
                setPatientInfo(patientDetail);
                patientRef.current?.update(patientDetail);
                setGoodsList(list);
                return {
                  data: list,
                  total: data.sum_record_num,
                  success: true,
                };
              } catch (error) {
                showMsg(error?.data?.errmsg);
                return {
                  data: [],
                  total: 0,
                  success: true,
                };
              }
            }}
            onValuesChange={(values, record) => {
              console.log(values, record);
              if (record) {
                const list = goodsList.map((item) => {
                  if (
                    item.detail_id === record.detail_id &&
                    record.cycle_num > 0 &&
                    item.goods_price > 0 &&
                    record.goods_num > 0
                  ) {
                    return {
                      ...item,
                      goods_total_price: parseFloat(parseFloat(record.cycle_num) * parseFloat(item.goods_price) * parseFloat(record.goods_num)).toFixed(2),
                    };
                  }
                  return {
                    ...item,
                  };
                });
                console.log(list);
                setGoodsList(list);
              }
            }}
            value={goodsList}
            dataSource={goodsList}
            actionRef={actionRef}
            onChange={(values) => {
              console.log(values);
              setGoodsList(values);
            }}
            recordCreatorProps={false}
            editable={{
              type: 'single',
              form,
              onSave: async (key, row) => {
                try {
                  await updateItem(row);
                  if (admission_num) {
                    fetchSum(admission_num);
                  }
                  return true;
                } catch (error) {
                  actionRef.current?.reload();
                  showMsg(error?.data?.errmsg);
                  return false;
                }
              },
              actionRender: (row, config, defaultDom) => [defaultDom.save, defaultDom.cancel],
              onCancel: async (key, row, originRow) => {
                console.log(key, row);
                form.resetFields();
                const list = goodsList.map((item) => {
                  if (item.detail_id === key) {
                    return {
                      ...item,
                      goods_total_price: parseFloat(parseFloat(originRow.cycle_num) * parseFloat(item.goods_price) * parseFloat(originRow.goods_num)).toFixed(2),
                    };
                  }
                  return {
                    ...item,
                  };
                });
                console.log(list);
                setGoodsList(list);
              },
            }}
            toolbar={{
              menu: {
                items: [
                  {
                    key: 'start',
                    label: (
                      <PermissionControl action_id="400402007">
                        <Button
                          disabled={!cansett}
                          loading={settleLoading}
                          onClick={async () => {
                            try {
                              if (admission_num) {
                                setSettleLoading(true);
                                await startSettle({ admission_num });
                                actionRef.current?.reload();
                                settleActionRef.current?.reload();
                                setSettleLoading(false);
                              }
                            } catch (error) {
                              showMsg(error?.data?.errmsg);
                              setSettleLoading(false);
                            }
                          }}
                          type="primary"
                        >
                          发起结算
                        </Button>
                      </PermissionControl>
                    ),
                  },
                  {
                    key: 'print',
                    label: (
                      <Button
                        disabled={isNull(goodsList)}
                        onClick={() => {
                          setRentListDialog(true);
                        }}
                        type="primary"
                      >
                        打印租赁清单
                      </Button>
                    ),
                  },
                ],
              },
            }}
            pagination={false}
            scroll={{
              x: 1000,
            }}
            columns={columns}
            onRow={record => {
              return {
                onClick: event => { setClickRow(record.detail_id) }, // 点击行
                onMouseEnter: event => {}, // 鼠标移入行
                onMouseLeave: event => {},
              };
            }}
            rowClassName={(record) => {
              return record.detail_id === clickRow ? 'tableRowClick' : ''
            }}
          />
        </Spin>
      </div>

      <div className="service-record-rent" style={{ marginTop: -10 }}>
        <div className="header">
          <div className="title">3.结算信息</div>
        </div>
        <Divider style={{ margin: '10px 0 0' }} />
        <Button 
          style={{ marginBottom: 5 }}
          disabled={isNull(params)}
          onClick={() => {
            fetchSum(admission_num);
            actionRef.current?.reload();
            settleActionRef.current?.reload();
          }} 
          icon={<ReloadOutlined />} 
          type="primary">
          刷新
        </Button>
        <Spin spinning={settleLoading}>
          <EditableProTable<any, COMMON.PageParams>
            rowKey="sett_id"
            bordered
            className="settle-pro-table"
            style={{ marginTop: -5 }}
            actionRef={settleActionRef}
            params={params}
            request={async (params) => {
              try {
                console.log('params', params)
                if (isNull(params.admission_num)) {
                  return {
                    data: [],
                    total: 0,
                    success: true,
                  };
                }
                params = Object.assign({}, params);
                const data = await getRentSettleInfo(params);
                return {
                  data: data.record_list,
                  total: data.sum_record_num,
                  success: true,
                };
              } catch (error) {
                showMsg(error?.data?.errmsg);
                return {
                  data: [],
                  total: 0,
                  success: true,
                };
              }
            }}
            recordCreatorProps={false}
            pagination={{
              showQuickJumper: true,
            }}
            columns={settleColumns}
            onRow={record => {
              console.log('record.sett_id', record.sett_id)
              return {
                onClick: event => { setClickRow1(record.sett_id) }, // 点击行
                onMouseEnter: event => {}, // 鼠标移入行
                onMouseLeave: event => {},
              };
            }}
            rowClassName={(record) => {
              return record.sett_id === clickRow1 ? 'tableRowClick' : ''
            }}
          />
        </Spin>
      </div>

      {dialogVisible && (
        <Detail
          handleModalVisible={(vis: boolean) => {
            setDialogVisible(vis);
            // 已结算，关闭弹窗不刷新
            if (currentRow.sett_status !== 'P') {
              settleActionRef.current?.reload();
              actionRef.current?.reload();
              fetchSum(admission_num);
            }
          }}
          title="查看结算单"
          optCallback={optCallback}
          record={currentRow}
          isPrint={printing}
          printCallBack={e => setPrinting(e)}
          rentType={3}
          cancelOrder={() => {
            cancelCurOrder(currentRow, line);
            setDialogVisible(false);
          }}
        />
      )}

      {rentListDialog && (
        <RentListDialog handleModalVisible={setRentListDialog} admission_num={admission_num} />
      )}
    </PageContainer>
  );
};
export default RentSettle;
